import qs from "qs";

export const HistoryUtils = (() => {

  const pathJoin = (...paths: (string | null | undefined)[]) => {
    let ret = paths.map((path, index) => {
      if (!path) {return index === 0 ? paths.length > 0 ? '' : '/' : '';}
      if (path.charAt(0) !== '/' && path.indexOf('http') !== 0) {path = '/' + path;}
      if (path.charAt(path.length - 1) == '/') {path = path.slice(0, -1);}
      return path;
    }).join('');
    if (!ret) {
      ret = '/';
    }
    return ret;
  };

  const decodePath = (url: string): { fullPath: string, path: string, hash: string, query: any } => {
    if (url.charAt(0) !== '/') {url = `/${url}`;}
    let path = "";
    let hash = "";
    let queryString = "";
    const [leftPart1, rightPart1] = url.split('?');
    path = leftPart1;
    if (!!rightPart1) {
      const [leftPart2, rightPart2] = rightPart1.split('#');
      queryString = leftPart2;
      hash = decodeURIComponent(rightPart2);
    }
    return { fullPath: decodeURIComponent(url), path, hash, query: !queryString ? {} : qs.parse(queryString) };
  };

  const getLocationMeta = () => {
    const { pathname, search, hash } = new URL(window.location.href);
    const fullPath = `${pathname}${search}${hash}`;
    return { pathname, search, hash, fullPath };
  };

  return {
    pathJoin,
    decodePath,
    getLocationMeta,
  };
})();

export interface iHistoryConfig {
  base: string,                     // publicPath部署路径
}

export interface iHistoryMeta {
  fullPath: string,                 // 全路径地址
  path: string,                     // 当前路径
  hash?: string,                    // 哈希值
  query?: Record<string, any>,      // 查询参数
}

export interface iHistoryHandler {
  getPath: (path: string) => string;// 从全路径中取出来需要解析成meta的字符串。hash路由解析的时候仅需要全路径中的hash
  push: (url: string) => void,      // 具体的push动作
}

export interface iChangeListener {
  (meta: iHistoryMeta): void;       // 监听器函数类型
}
